package com.jmb.api.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.jmb.api.common.exception.ParseException;

import java.util.HashMap;
import java.util.List;

public class JsonUtil {
    public static List jsonString2List(String jsonString) throws ParseException {
        List var1;
        try {
            var1 = JSONObject.parseObject(jsonString, List.class);
        } catch (Exception e) {
            throw new ParseException("JSON解析为列表时出现异常: " + e.getMessage());
        }
        return var1;
    }

    public static JSONObject jsonString2Object(String jsonString) throws ParseException {
        JSONObject var1;
        try {
            var1 = JSONObject.parseObject(jsonString);
        } catch (Exception e) {
            throw new ParseException("Json解析为JSONObject时出现异常: " + e.getMessage());
        }
        return var1;
    }

    public static HashMap jsonString2HashMap(String jsonString) throws ParseException {
        HashMap var1;
        try {
            var1 = JSONObject.parseObject(jsonString, HashMap.class);
        } catch (Exception e) {
            throw new ParseException("JSON解析为Map时出现异常: " + e.getMessage());
        }
        return var1;
    }

    public static Object getJsonArrayIndex(String jsonString, int index) throws ParseException {
        if (index < 0) {
            throw new ParseException("index 非法：index: " + index);
        }
        List var1 = jsonString2List(jsonString);
        if (index >= var1.size()) {
            throw new ParseException("index 越界: Index: " + index + ", Size: " + var1.size());
        }
        return var1.get(index);
    }

    public static Object getJsonArrayIndex(String jsonString, int index, String defaultValue) throws ParseException {
        if (defaultValue == null) {
            throw new ParseException("默认值不应为空");
        }
        if (index < 0) {
            return defaultValue;
        }
        List var1 = jsonString2List(jsonString);
        if (index >= var1.size()) {
            return defaultValue;
        }
        return var1.get(index);
    }
    // 将JSON字符串转成HASH Map
    public static HashMap<String,Object> parseJsonToMap(String json){
        if (json==null){
            return new HashMap<>();
        }
        try {
            return JSONObject.parseObject(json,new TypeReference<HashMap<String,Object>>(){});
        }catch (Exception e){
            // 处理解析异常，返回空Map
            return new HashMap<>();
        }
    }
}
